from heap.class_klass import HeapObject


class JString:
    CONSTANT_STR_POOL = {}

    @staticmethod
    def internal(cl, string: str) -> HeapObject:
        if string in JString.CONSTANT_STR_POOL.keys():
            return JString.CONSTANT_STR_POOL[string]
        obj = HeapObject()
        obj.set_class(cl.loadClass(className="[C"))
        obj.set_data(string.encode("utf-8"))
        jstr = cl.loadClass("java/lang/String").newHeapClass()
        jstr.setRefVar("value", "[C", obj)
        JString.CONSTANT_STR_POOL[string] = jstr
        return jstr
